﻿using System;
using System.Collections;
using System.Data.Entity;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Noria.Web.MyMSDN;
using Noria.Web.MyMSDN.Models;
using Noria.Web.Utility;
using MmContext = Noria.Web.MyMSDN.Models.MmContext;

namespace Noria.Web.Test
{
    [TestClass]
    public class HttpBotTest
    {
        private static readonly log4net.ILog slog = log4net.LogManager.GetLogger("Noria.Spider");

        private static readonly string rootMSDN = (string)NConfig.Root.spider.settings.msdn;
        private static readonly string urlCategory = rootMSDN + "/en-us/subscriptions/json/GetProductCategories?brand=MSDN&localeCode=en-us";
        private static readonly string urlFamily = rootMSDN + "/en-us/subscriptions/json/GetProductFamiliesForCategory?brand=MSDN&categoryId={0}";
        private static readonly string urlSearch = rootMSDN + "/en-us/subscriptions/json/GetFileSearchResult";

        [TestMethod]
        public void GZipTest()
        {
            //dynamic json = HttpBot.RequestJArray(null,
            //    "http://msdn.microsoft.com/en-us/subscriptions/json/GetProductFamiliesForCategory?brand=MSDN&categoryId=1");

            //var ProductFamilyId = (int)json[0].ProductFamilyId;

            //dynamic json2 = HttpBot.RequestJArray(null,
            //    "http://msdn.microsoft.com/en-us/subscriptions/json/GetProductCategories?brand=MSDN&localeCode=en-us");

            //var ProductGroupId = (int)json2[0].ProductGroupId;

            var ss = HttpBot.RequestText(null, "http://cdn.sstatic.net/stackoverflow/all.css?v=1748204ca390");
            var s2 = HttpBot.RequestText(null, "http://anjieart.net/");
        }

        [TestMethod]
        public void GetLocaleForWin7()
        {
            dynamic root = new ExpandoObject();

            using (var db = new MmContext())
            {
                // 'Operating Systems'
                var tmp = db.Categories.Where(p => p.CategoryId == 36).Include("Families").ToArray();
                root.Categories = tmp;

                // 'Windows 7'
                tmp.First().Families = tmp.First().Families.Where(p => p.FamilyId == 350).ToList();
            }


            var cats = root.Categories as IEnumerable;
            foreach (Category cat in cats)
            {
                Parallel.ForEach(cat.Families, (family, state) =>
                {
                    var body = CreateSearchPayload(family.FamilyId, "en");
                    dynamic payload;

                    try
                    {
                        payload = HttpBot.RequestJObject(null, urlSearch, Encoding.UTF8.GetBytes(body), "application/json");
                    }
                    catch (Exception e)
                    {
                        slog.Error("Failed to retrieve file from family " + family.Name, e);
                        throw;
                    }

                    foreach (dynamic locale in (IEnumerable)payload.LanguageContext)
                    {
                        slog.InfoFormat(",{0},{1}", (string)locale.DisplayName, (string)locale.Value);
                    }


                });
            }

        }

        [TestMethod]
        public void GetLocaleForWin8()
        {
            dynamic root = new ExpandoObject();

            using (var db = new MmContext())
            {
                // 'Operating Systems'
                var tmp = db.Categories.Where(p => p.CategoryId == 36).Include("Families").ToArray();
                root.Categories = tmp;

                // 'Windows 7'
                tmp.First().Families = tmp.First().Families.Where(p => p.FamilyId == 481).ToList();
            }


            var cats = root.Categories as IEnumerable;
            foreach (Category cat in cats)
            {
                Parallel.ForEach(cat.Families, (family, state) =>
                {
                    var body = CreateSearchPayload(family.FamilyId, "en");
                    dynamic payload;

                    try
                    {
                        using (var stat = new SimpleStatistics("test"))
                        {
                            payload = HttpBot.RequestJObject(stat, urlSearch, Encoding.UTF8.GetBytes(body), "application/json");
                        }
                    }
                    catch (Exception e)
                    {
                        slog.Error("Failed to retrieve file from family " + family.Name, e);
                        throw;
                    }

                    foreach (dynamic locale in (IEnumerable)payload.LanguageContext)
                    {
                        slog.InfoFormat(",{0},{1}", (string)locale.DisplayName, (string)locale.Value);
                    }


                });
            }
        }

        private string CreateSearchPayload(long familyId, string locale)
        {
            using (var db = new MmContext())
            {
                locale = string.Join(",", db.Locales.Where(p => p.Enabled).Select(p => p.Code).ToArray());
            }


            dynamic payload = new JObject();

            payload.Languages = locale;
            payload.Architectures = "";
            payload.ProductFamilyIds = "";
            payload.FileExtensions = "";
            payload.MyProducts = false;
            payload.ProductFamilyId = familyId;
            payload.SearchTerm = "";
            payload.Brand = "MSDN";
            payload.PageIndex = 0;
            payload.PageSize = 5000;
            payload.FileId = 0;

            return ((JObject)payload).ToString(Formatting.None);
        }



    }
}
